var hashLocalidad = [];
var hashIcons = [
  'ico/0.png',
  'ico/1.png',
  'ico/2.png',
  'ico/3.png',
  'ico/4.png',
  'ico/5.png',
  'ico/6.png',
  'ico/7.png',
];

var Request = (function () {
  return {
    allMarkers : function () {
      var types = [
        {
          serverCall : 'listar_localidades_en_area_cuadrada',
          icon : 'ico/7.png'
        }, {
          serverCall : 'listar_lugares_en_area_cuadrada',
          icon : 'ico/1.png'
        }, {
          serverCall : 'listar_medios_de_transporte_en_area_cuadrada',
          icon : 'ico/0.png'
        }, {
          serverCall : 'listar_paradas_dentro_de_area_cuadrada',
          icon : 'ico/4.png'
        }],
          i;

      for (i=0; i<types.length; i++) {
        this.oneMarker(types[i].serverCall, types[i].icon);
      }
    },
    oneMarker : function (serverCall, icon) {
      var bounds = GoogleMap.obtenerBounds(),
          data = {x1 : bounds[0].lng, x2 : bounds[1].lng,
                  y1 : bounds[0].lat, y2 : bounds[1].lat};

      $.ajax({
        url : serverCall,
        type : 'post',
        data : data,

        success : function (data) {
          var markersRequest = [],
              i;

          data = JSON.parse(data);

          for (i=0; i<data.length; i++) {
            markersRequest[i] = {
              lat : parseFloat(data[i].latitud),
              lng : parseFloat(data[i].longitud),
              img : icon,
              datos : data[i]
            };
          }

          GoogleMap.cargarMarcadores(markersRequest);
        }
      });
    },

    /**
     * el contexto de esta función es un marcador.
     * consulta la información, y la escribe en el
     * formulario respectivo
     */
    consultarMarcador : function () {
      var index = hashIcons.indexOf(this.getIcon()),
          info = $( '.info-' + index + ' input'),
          i,
          property;
      Info.spawnNewFor(index);

      asdf = this.data;      
      for (i=0; i<info.length; i++) {
        for (property in this.data) {
          if (this.data.hasOwnProperty(property)) {
            $( '[name="' + property + '"]' ).val(this.data[property]);
          }
        }
      }
    }
  };
})();

var AddAction = (function () {
  return {
    select : function (index) {
      this.selected = $( '#mouse-image' );
      this.index = index;

      if (index === '6') {
        // cancel action
        this.selected.attr('hidden', true);
        this.selected.attr('src', 'none');
      } else {
        this.selected.attr('src', 'ico/' + index + '.png');
        this.selected.removeAttr('hidden');
      }
    },
    add : function (latLng, data) {
      var marker;

      if (this.lastAddedItem) {
        console.log(this.lastAddedItem, this.lastAddedItem.id);
        if (!this.lastAddedItem.id) {
          // this.lastAddedItem.marker.setMap(null);
        }
      }

      if (this.index !== 6) {
        marker =
          selectedMarker = GoogleMap.addMarker('ico/' + this.index + '.png',
                                               latLng, data);
        Info.spawnNewFor(this.index);

        var latInput = $('.info-' + this.index + ' [name="latitud"]').
            val(latLng.lat()),

            lngInput = $('.info-' + this.index + ' [name="longitud"]').
            val(latLng.lng());
        var item = mapControllers[this.index].create();
        item.initialize();
        item.marker = marker;
        this.lastAddedItem = item;
      }

    }
  };
})();

var Info = (function () {
  return {
    spawnNewFor : function (index) {
      var children,
          child;
      if (this.spawned) {
        this.spawned.attr('hidden', true);
        children = $( this.spawned.selector + ' input' );
        children.push($( this.spawned.selector + ' textarea ' ));

        for (i=0; i<children.length; i++) {
          child = $(children[i]);

          if (child.attr('name') !== '_token' &&
              child.attr('name') !== 'id_dep' &&
              child.attr('name') !== 'lista_departamentos') {
            child.val('');
          }
        }
      }
      this.spawned = $( '.info-' + index);
      this.spawned.removeAttr('hidden');

      return this.spawned;
    }
  };
})();


// on window ready. This is executed at first ;)
$( window ).ready(function () {
  /**
   * listens to the icons click, so it can
   * change the addition activity.
   */
  $( '.action-list' ).mousedown(function (e) {
    AddAction.select($( this ).children().attr('name'));
  });

  /**
   * selected icon follows the mouse.
   * the selected icon is contained on a hidden image.
   */
  $( document ).mousemove(function (e) {
    $("#mouse-image").css({left:e.clientX + 10, top:e.clientY + 10});
  });

  // this is the selected icon :D
  $( 'body' ).append("<img src='none' id='mouse-image' hidden>");


  // creates the localidades dropdown.
  $.ajax({
    url : 'l_localidades_id_nombre',
    type : 'get',

    success : function (data) {
      data = JSON.parse(data);
      var i;
      for (i=0; i<data.length; i++) {
        $( '[name="localidades"]' )
          .append("<option>" + data[i].nombre + "</option>");
        hashLocalidad[data[i].id_localidad] = data[i].nombre;
      }
    }
  });
});






google.maps.event.addDomListener(window, 'load', GoogleMap.initMap);
